package com.sunran;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


@Path("folders")
public class FolderResource  {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public Map addFolder(@FormParam("currentPath") String currentPath, @FormParam("newFolderName") String newFolderName){
        File file = new File(currentPath);
        Map<String,String> map = new HashMap<>();
        if(!file.exists()){
            map.put("state","failed");
            map.put("msg","创建文件夹失败");
            return map;
        }
        String path = currentPath+newFolderName;
        file = new File(path);
        file.mkdirs();
        map.put("state","success");
        map.put("msg","创建文件夹成功");
        return map;
    }

    @DELETE
    @Produces(MediaType.APPLICATION_JSON)
    public Map removeFolder(@QueryParam("currentPath") String currentPath){
        File file = new File(currentPath);
        Map<String,String> map = new HashMap<>();
        if (!file.exists()) {
            map.put("state","failed");
            map.put("msg","删除文件夹失败");
            return map;
        }
        deleteFiles(file);
        file.delete();
        map.put("state","success");
        map.put("msg","删除文件夹成功");
        return map;
    }



    public void deleteFiles(File file){
        if(!file.isDirectory()){
            file.delete();
            return;
        }
        for(File fileItem : file.listFiles()){
            deleteFiles(fileItem);
        }
    }
}
